<?php
if(!defined('IN_MANU')) {
	die('[ERROR] You cannot load this page directly !!!');
}

Class Template {
	/*
	 * @the registry
	* @access private
	*/
	private $configuration  = array();

	private $registry       = null;

	/*
	 * @Variables array
	* @access private
	*/
	private $vars           = array();
	private $moduleTags     = array();

	// 	private $menuKey = '';
	private $menuKeyACP = '';

	/**
	 *
	 * @constructor
	 *
	 * @access public
	 *
	 * @return void
	 *
	 */
	function __construct($registry) {
		//print_r($registry);
		$this->registry = $registry;

		include('views/configuration.php');

		$this->configuration = $template;
	}


	/**
	 *
	 * @set undefined vars
	 *
	 * @param string $index
	 *
	 * @param mixed $value
	 *
	 * @return void
	 *
	 */
	public function __set($index, $value)
	{
		$this->vars[$index] = $value;
	}


	public function getTemplate($name, array $tags = array(), $type)
	{
		$tags['manuPath']	  = dirname(MANU_ROOT_PATH);
		$tags['manuRootPath'] = MANU_ROOT_PATH;
		$tags['manuViewPath'] = MANU_ROOT_PATH . 'views/';

		$tags = $this->getMenuTemplateReplace($tags);

		$path = MANU_PATH . '/views' . '/' . $name . $type . '.php';

		if (file_exists($path) == false){
			throw new Exception('Template not found in '. $path);
			return false;
		}

		//echo $tags['bstoViewPath']."\n";
		$template = file_get_contents($path);
		foreach($tags as $tag => $value){
			$template = str_replace('{'.$tag.'}', $value, $template);
		}
		return $template;
	}

	public function getModule($name, array $tags = array())	{
		return $this->getTemplate($name, $tags, 'Module');
	}

	public function getView($name, array $tags = array()){
		return $this->getTemplate($name, $tags, 'View');
	}

	private function includeCSS()
	{
		$result = '';
			
		$cssFile = $this->configuration['css_files'];
		foreach($cssFile as $value)
		$result .= '<link rel="stylesheet" href="' . MANU_ROOT_PATH . 'views/' . $this->configuration['css_dir'] . $value. '" type="text/css" media="screen" />';

		return $result;
	}


	private function includeExtraCSS()
	{
		$result = '';
		$cssFile = $this->configuration['extra_css_files'];
		$cond = $cssFile[0];
		for($i = 1; $i < count($cssFile); $i++){
			$result .= '
<!--[if $cond>
<link rel="stylesheet" href="' . MANU_ROOT_PATH . 'views/' . $this->configuration['css_dir'] . $cssFile[$i]. '" type="text/css" media="screen" />
<![endif]-->
';
		}
		return $result;
	}

	private function includeJS()
	{

		$result = '';

		$jsFile = $this->configuration['js_files'];
		foreach($jsFile as $value)
		$result .= '<script src="' . MANU_ROOT_PATH . 'views/' . $this->configuration['js_dir'] . $value. '" type="text/javascript"></script>';

		return $result;
	}

	private function addCustomJS($flag)
	{
		if(!$flag){
			$result = '
<script type="text/javascript">
    var fileLoadingImage = "'.$this->registry->router->getRoot().'views/images/loading.gif";		
    var fileBottomNavCloseImage = "'.$this->registry->router->getRoot().'views/images/closelabel.gif";
    var varUploadBtn = "'.$this->registry->router->getRoot().'views/images/forms/upload_file.gif";
    var ImageURL = "'.$this->registry->router->getRoot().'views/images/forms/calendarIcon.jpg";
    var NextURL = "'.$this->registry->router->getRoot().'views/images/forms/calendarNext.gif";
    var PrevURL = "'.$this->registry->router->getRoot().'views/images/forms/calendarPrev.gif";
    var ajaxUrl = "'.$this->registry->router->getRoot().'";
    var bookPath = "'.$this->registry->router->getRoot().'book";
</script>
';
		}
		else {
			$result = '';
		}
		return $result;
	}

	private function getPageHeaderTag()
	{
		return $this->addCustomJS(false) . $this->includeCSS()  . $this->includeJS();
	}

	public function setMenuKey($key)
	{
		$this->menuKeyACP = $key;
	}



	public function getMenuTemplateReplace($tags)
	{
		$tags['user']           = 'select';
		$tags['role']           = 'select';
		$tags['privilege']      = 'select';
		$tags['profile']        = 'select';

		$tags['userShow']       = '';
		$tags['roleShow']       = '';
		$tags['privilegeShow']  = '';
		$tags['profileShow']    = '';
			
		$tags[$this->menuKeyACP]        = 'current';
		$tags[$this->menuKeyACP . 'Show'] = ' show';
		return $tags;
	}

	public function getPageContent($name, $title, $content, array $tags = array())
	{
		// current User
		$tags['username'] = $this->registry->db->get('userManager')->getCurrentUser();
		//$userType = $user->get('type');

		//just for test
		$user = 'test';
		$userType = 'Admin';

		$tags['manuFullAdminMenu'] = $this->getModule('fullmenu', $tags);

		//$tags['username'] = $user->get('username');
		//$tags['username'] = 'test';

		$moduleTags = array('manuHeader'    => $this->getPageHeaderTag(),
                            'manuMenu'      => $this->getModule('menu', $tags),
                            'manuFooter'    => $this->getModule('footer', $tags),
                            'manuContent'	=> $content,
            		    	'manuContentTitle' => $tags['manuContentTitle'],
            		    	'manuMessage' 	=> $tags['manuMessage']            										
		);

		// get appropriate template
		$result = $this->getView($name, $moduleTags);

		// return output
		return str_replace('{manuTitle}', $title, $result);
	}

	public function getTableHeader(array $atts = array())
	{
		if (count($atts) == 0) {
			return null;
		}
		
		$res = '<tr><th class="table-header-check"><a id="toggle-all" ></a></th>' ;
		foreach ($atts as $val) {
			$res .= '<th class="table-header-repeat line-left"><a>' . $val . '</a></th>';
		}
		$res .= '<th class="table-header-options line-left"><a>OPTIONS</a></th></tr>';

		return $res;
	}

	public function getTableRow($atts = array(), $obj = null, $alterRow = false, $type = null, $grant = false)
	{
		//echo "dasdas";
		$num = count($atts);
		
		
		if (($obj == null) | ($num == 0)) {
			return null;
		}
		
		if ($alterRow) //differentiate rows with color
			$res = '<tr class="alternate-row"><td><input  type="checkbox"/></td>';
		else
			$res = '<tr><td><input  type="checkbox"/></td>';
		// put link into name
		$name = $obj->get(strtoupper($atts[0]));
		$res .= '<td><a href="{path}/view/' . $name . '">' . $name . '</a></td>';
		// get other values
		if($type == 'privilege' || $grant == true)
			$opt = $this->getModule('optionfield1', array('manuName' => $name));
		else 
			$opt = $this->getModule('optionfield', array('manuName' => $name));
		
		for ($i = 1; $i < $num; $i++) {
			$fieldName = strtoupper($atts[$i]);
			$val = $obj->get($fieldName);
			$res .= '<td>' . $val . '</td>'; 
			
			if (($grant == true) && ($fieldName == 'TABLE_NAME')) {
				$name .= "/$val";				
				$opt = $this->getModule('optionfield1', array('manuName' => $name));
			}
			if (($fieldName == 'ADMIN_OPTION' || $fieldName == 'GRANTABLE') && $val == 'NO')
					$opt = $this->getModule('optionfield2', array('manuName' => $name));			
		}
		
		$res .= $opt;
		$res .= '</tr>';

		return $res;
	}
	
	public function getDetailTable(array $atts = array(), $rows = null)
	{
		// table's header
		$header = '<tr>';
		foreach ($atts as $val) {
			$header .= '<th>' . $val . '</th>'; 
		}
		$header .= '</tr>';
		
		// table's body
		$body = '';
		foreach ($rows as $obj) {
			$body .= '<tr>';
			foreach ($atts as $val) {
				$body .= '<td>' . $obj->get(strtoupper($val)) . '</td>'; 
			}
			$body .= '</tr>';
		}
		
		$tags = array('manuTableHeader' => $header ,
					  'manuTableContent' => $body);
		
		$tbl = $this->getModule('table', $tags);
		
		return $tbl;
	}
}

?>
